<?php
	// Function to get the client ip address
	function get_client_ip() {
		$ipaddress = '';
		if (getenv('HTTP_CLIENT_IP'))
			$ipaddress = getenv('HTTP_CLIENT_IP');
		else if(getenv('HTTP_X_FORWARDED_FOR'))
			$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
		else if(getenv('HTTP_X_FORWARDED'))
			$ipaddress = getenv('HTTP_X_FORWARDED');
		else if(getenv('HTTP_FORWARDED_FOR'))
			$ipaddress = getenv('HTTP_FORWARDED_FOR');
		else if(getenv('HTTP_FORWARDED'))
			$ipaddress = getenv('HTTP_FORWARDED');
		else if(getenv('REMOTE_ADDR'))
			$ipaddress = getenv('REMOTE_ADDR');
		else
			$ipaddress = 'UNKNOWN';
	 
		return $ipaddress;
	}
	// redirect to other page
	function redirectTo($page)
	{
		header("location:{$page}");
		exit;	
	}
	// redirect to other page
	function pageRedirect ($urlLink, $msgStatus = ""){
	if ($msgStatus != ""){$msgStatus = "msgStatus=".$msgStatus;}	
	echo "<script>window.location='$urlLink".$msgStatus."';</script>";	
	}
	//show global message
	function errorMessage($error)
	{
		global $errors;
		$error = "<div style='color:red;  padding:5px; margin:3px; float:left;
		font:bold 12px Arial;'>$error</div>";
		$errors .= $error;
		return $errors;
	}
	//add / to special character
	function escapeValue($value)
	{
		if(function_exists("mysql_real_escape_string"))
		{
			if(get_magic_quotes_gpc())
			{
				$value = stripslashes($value);	
			}
			$value = mysql_real_escape_string($value);
		}
		else
		{
			if(!get_magic_quotes_gpc())
			{
				$value = addslashes($value);	
			}
		}
		return $value;
	}
	function getParameter($method, $para,$default=""){
	if ($method == "get"){
		if (isset($_GET[$para])){
			$v = $_GET[$para];	
		}else{
			$v = $default;		
		}		
	}else{
		if (isset($_POST[$para])){
			$v = $_POST[$para];	
		}else{
			$v = $default;		
		}		
	}
	return $v;
}
//stay in current page
function pageVisited($page, $menu){
	if ($page == $menu){
		echo 'class="visited" ';
	}
}
//stay in current page
function pageVisited_($page, $menu){
	if ($page == $menu){
		echo ' style="color:#F00" ';
	}
}
	function page($page){
		echo $page;
	}
	//find max id
	function maxOfAll($column, $table)
    {
      $sql=("SELECT MAX($column) FROM $table");
	  $result=query($sql);
	  $row=fetch_array($result);
	  return $row[0];
	   
    }
	function maxOfAll1($column, $table)
    {
      $sql=("SELECT MAX($column) FROM $table");
	  $result=mysql_query($sql);
	  $row=mysql_fetch_array($result);
	  return $row[0];
	   
    }
	//find min id
	function minOfAll($column, $table)
    {
      $sql=("SELECT MIN($column) FROM $table");
	  $result=query($sql);
	  $row=fetch_array($result);
	  return $row[0];
	   
    }
	function maxOf($column, $table, $where)
    {
	  $sql=("SELECT MAX(`$column`) FROM `$table` WHERE $where");
	  $result=query($sql);
	  $row=fetch_array($result);
	  return $row[0];
    }
	function minOf($column, $table, $where)
    {
	  $sql=("SELECT MAX(`$column`) FROM `$table` WHERE $where");
	  $result=query($sql);
	  $row=fetch_array($result);
	  return $row[0];
    }
	function countOf($table, $where)
    {
	  $sql=("SELECT COUNT(*) FROM `$table` WHERE $where");
	  $result=query($sql);
	  $row=fetch_array($result);
	  return $row[0];
    }
    function countOfAll($table)
    {
	  $sql=("SELECT COUNT(*) FROM $table");
	  $result=query($sql);
	  $row=fetch_array($result);
	  return $row[0];
    }
	function sumOfAll($column,$table)
    {
	  $sql=("SELECT sum($column) FROM $table ");
	  $result=query($sql);
	  $row=fetch_array($result);
	  return $row[0];
    }
	function sumOf($column,$table,$where)
    {
	  $sql=("SELECT sum($column) FROM $table WHERE $where");
	  $result=query($sql);
	  $row=fetch_array($result);
	  return $row[0];
    }
	/**
	 * Returns the list
	 *
	 */
	function get($table,$where = FALSE , $field_order = FALSE, $options = FALSE,$trace=FALSE) //$where get by condition // $orderby (Field Name) //$options (ASC or DESC)
	{
		//concentenate where
		if($where==TRUE){
			foreach ($where as $field=>$value) {
				$where= "WHERE " . $field . "='" . mysql_real_escape_string($value) . "'";
			}
		}
		//concentenate where
		if($field_order==TRUE){
			 $field_order= " ORDER BY " . $field_order ;
		}
		$query = "SELECT * FROM $table  $where   $field_order   $options";
		$result=query($query);
		if($trace == 'trace')
			print_r($query);
		if(!empty($result))
		{
		  if ( num_rows($result) > 0 )
			  while($row = fetch_array($result))
			  {
				//convert data to array
				$rows[] = $row;
			  }
		  return $rows;	
		}
	}
	/**
	 * Returns the record by one field
	 *
	 */
	function get_by_sql($sql, $option=false)
	{
		$query	= query($sql);
		if($option == 'trace')
			print_r($sql);			
		if(!empty($query))
		{
			if ( num_rows($query) > 0 )
				while($row = fetch_array($query))
				{
				  //convert data to array
				  $rows[] = $row;
				}
			return $rows;	
		}
	}
	/**
	 * Check Duplicate
	 *
	 */ 	 
	function duplicate($table, $where=FALSE)
	{	
		//concentenate where
		if($where==TRUE){
			foreach ($where as $field=>$value) {
				$where= "WHERE " . $field . "='" . mysql_real_escape_string($value) . "'";
			}
		}
		// check record
		$sql=("SELECT * FROM $table $where");
		$result=query($sql);	
		if(!empty($result)):
			if (num_rows($result) > 0 )
				return true;
			else
				return false;
		endif;
		
		return false;
	}
	
	/**
	 * delete data
	 *
	 */ 	 
	function delete_data($table, $where=FALSE)
	{	
		//concentenate where
		if($where==TRUE){
			foreach ($where as $field=>$value) {
				$where= "WHERE " . $field . "='" . mysql_real_escape_string($value) . "'";
			}
		}
		// delete data
		$sql=("DELETE FROM $table  $where");
		$result=query($sql);
		if(!empty($result)){
				return true;
		}else
		{
			return true;
		}	
	}
	/*
		save activity of user
	*/
	function saveActivityLog($module, $message, $user,$option=false)
	{	
		$date_entry=date('Y-m-d H:i:s'); 
		$ip=get_client_ip();
		$sql=("INSERT INTO activity_log(entry_date,from_ip,username,module,message)  
			  VALUES ('$date_entry','$ip','$user','$module','$message')");
		$affected_rows=query($sql);
		if($option == 'trace')
			print($sql);	
		return $affected_rows;			
	}
	/*
		save data to DB
	*/
	function insert($table, $data) {
		foreach ($data as $field=>$value) {
			$fields[] = "" . $field . "";
			$values[] = "'" . mysql_real_escape_string($value) . "'";
		}
		$field_list = join(',', $fields);
		$value_list = join(', ', $values);
		
		$sql = "INSERT INTO " . $table . " (" . $field_list . ") VALUES (" . $value_list . ")";
		$affected_rows=query($sql);
		return $affected_rows;
	}
	/*
		update data to DB
	*/
	function update($table, $data, $where) {
		//concentenate fields
		foreach ($data as $field=>$value) {
			$fields[] = " " . $field . "='" . mysql_real_escape_string($value) . "'";
		}
		$field_list = join(',', $fields);
		//concentenate where
		foreach ($where as $field=>$value) {
			$where= "" . $field . "='" . mysql_real_escape_string($value) . "'";
		}
		$sql = "UPDATE " . $table . " SET  ". $field_list ." WHERE " . $where ;
		$affected_rows=query($sql);
		return $affected_rows;
	}
	/**
	 * check permission of controller
	 *
	 */
	function has_permission($controller_name)
	{
		//check group of user, if group=1 then full control
		if(getGroupUser()==1)
			return true;
		
		//get controller id by name
		$sql=("SELECT * FROM controllers WHERE name='".$controller_name."'");
		$row=query($sql);
		$get_controller=fetch_array($row);
					
		if(count($get_controller)>0)
		{
			// check permission
			$sql="SELECT * FROM controllers_permission WHERE user_id='". getUserId() ."' AND ". " controller_id='".$get_controller['id']."'";
			$result=query($sql);
			
			while($row = fetch_array($result))
			{
				//convert data to array
				$rows[] = $row;
			}

			if(count($rows)>0){
				return true;}
			else{
				return false;}
		}
		
		else
			return false;
	}
	/**
	 * @encode string
*/
function encrypt($input) {
    return strtr(base64_encode($input), '+/=', '-_,');
}
/**
	 * @decode string
 */
function decrypt($input) {
    return base64_decode(strtr($input, '-_,', '+/='));
}  
 /**
 	* Pagination
 */
function pagination($query, $per_page = 10,$page = 1, $url = false){ 
	if($url == false){
		$url = '?';
	}       
	$query = "SELECT COUNT(*) as `num` FROM {$query}";
	//print_r($query);
	$row = mysql_fetch_array(mysql_query($query));
	$total = $row['num'];
	$adjacents = "2"; 

	$page = ($page == 0 ? 1 : $page);  
	$start = ($page - 1) * $per_page;								
	
	$prev = $page - 1;							
	$next = $page + 1;
	$lastpage = ceil($total/$per_page);
	$lpm1 = $lastpage - 1;
	
	$pagination = "";
	if($lastpage > 1)
	{	
		$pagination .= "<ul class='pagination'>";
				$pagination .= "<li class='details'>Page $page of $lastpage</li>";
		if ($lastpage < 7 + ($adjacents * 2))
		{	
			for ($counter = 1; $counter <= $lastpage; $counter++)
			{
				if ($counter == $page)
					$pagination.= "<li><a class='current'>$counter</a></li>";
				else
					$pagination.= "<li><a href='{$url}page=$counter'>$counter</a></li>";					
			}
		}
		elseif($lastpage > 5 + ($adjacents * 2))
		{
			if($page < 1 + ($adjacents * 2))		
			{
				for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
				{
					if ($counter == $page)
						$pagination.= "<li><a class='current'>$counter</a></li>";
					else
						$pagination.= "<li><a href='{$url}page=$counter'>$counter</a></li>";					
				}
				$pagination.= "<li class='dot'>...</li>";
				$pagination.= "<li><a href='{$url}page=$lpm1'>$lpm1</a></li>";
				$pagination.= "<li><a href='{$url}page=$lastpage'>$lastpage</a></li>";		
			}
			elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
			{
				$pagination.= "<li><a href='{$url}page=1'>1</a></li>";
				$pagination.= "<li><a href='{$url}page=2'>2</a></li>";
				$pagination.= "<li class='dot'>...</li>";
				for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
				{
					if ($counter == $page)
						$pagination.= "<li><a class='current'>$counter</a></li>";
					else
						$pagination.= "<li><a href='{$url}page=$counter'>$counter</a></li>";					
				}
				$pagination.= "<li class='dot'>..</li>";
				$pagination.= "<li><a href='{$url}page=$lpm1'>$lpm1</a></li>";
				$pagination.= "<li><a href='{$url}page=$lastpage'>$lastpage</a></li>";		
			}
			else
			{
				$pagination.= "<li><a href='{$url}page=1'>1</a></li>";
				$pagination.= "<li><a href='{$url}page=2'>2</a></li>";
				$pagination.= "<li class='dot'>..</li>";
				for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
				{
					if ($counter == $page)
						$pagination.= "<li><a class='current'>$counter</a></li>";
					else
						$pagination.= "<li><a href='{$url}page=$counter'>$counter</a></li>";					
				}
			}
		}
		
		if ($page < $counter - 1){ 
			$pagination.= "<li><a href='{$url}page=$next'>Next</a></li>";
			$pagination.= "<li><a href='{$url}page=$lastpage'>Last</a></li>";
		}else{
			$pagination.= "<li><a class='current'>Next</a></li>";
			$pagination.= "<li><a class='current'>Last</a></li>";
		}
		$pagination.= "</ul>\n";		
	}
	return $pagination;
} 
?>
